from . import admins_bp
from .forms.category import EditForm
from ...helper import redirect_back
from ...models import Category, db
from flask import render_template, flash


@admins_bp.route('/category')
def category_select():
    record = Category.html_tree(pid=0)
    return render_template(
        'category_select.html',
        record=record,
        page_title='栏目管理'
    )


@admins_bp.route('/category/create', methods=['GET', 'POST'])
def category_create():
    form = EditForm()
    if form.validate_on_submit():
        with db.auto_commit():
            Category.create(form.data)
        flash('新增成功', 'success')
        return redirect_back('admins.category_select')
    return render_template('category_edit.html', form=form, page_title='新增编辑')


@admins_bp.route('/category/<int:category_id>/modify', methods=['GET', 'POST'])
def category_modify(category_id):
    category = Category.query.get_or_404(category_id)
    form = EditForm(**category.__dict__)
    if form.validate_on_submit():
        with db.auto_commit():
            category.update(form.data)
        flash('更新成功', 'success')
        return redirect_back('admins.category_select')
    return render_template('category_edit.html', form=form, page_title='更新栏目')